package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sun.deploy.net.HttpResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@RestController
public class AlipayController {

    @RequestMapping("/pay")
    public   void   pay (HttpServletRequest httpRequest,
                         HttpServletResponse httpResponse)   throws ServletException, IOException {
        AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipaydev.com/gateway.do","2021000119610462", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQClDBhLKKfa4NBFgosi/FB076zoK74Jqt8jNrdZnOHoR+pi72MnVU0EIily6XlZzVDgcefvNOdwHrbTOwz0gFd6wE4/lja5fCe9jreNelwQjKlOfVytM0jLxc+yuFcMw72h9/gpAlFrhimKeooAOcUbOXF71bC8azQgaCIPmUdkceEBBmAwsHUDhokdbJ7itk42g6l11TA1o1bJXWy8RtakoGHZYqtuAVeNfE9A9cxdwQOdCNv4wjGacwFcwJqlWqJiSCocbpRNOaZsNZGwXeWemk6XOK4YmNsZUHbGVDR40Q7+QJzeDnNyH7nhY8Ys20uAU/TNoTahQ1gwBqBUHhWZAgMBAAECggEAQjnVMatRlzEoQQv9un8V5aYaclrC+WwX9zBIZ+vcdfENar91wN2odqUijpqCd/c7oaPzFffbehDI+X8zVpR9BaNOgpNKyCi6ZYRzwJA9iuJ2OSlyW4k9h46LJcJ0I4oTeH9gk0v70bJWztsWrrp/jcoB8FexgBlgJDTEng+6JuIpnCCt3a8z9SnlLZxb+WZtMPMAhPOBuJ5Cg1/7zEyFBjRaakVVwmffrAFME9HQ+rr6gvuJc88KYVoNwUOxkfb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GYm1GMxzyAgTeMDEyrJGJUsGjiIAuY8Elv/nlqIdhzw27+OVSZWGUcWjXgFkg6ie7o87fwJG0roCkDRpR8+s5jYMDR54P1DPhHwjTGHviNSaGGJFNV9VKiB4//Mt5mSiD7HeiqT5CqVmhj6YtkZ+ydM0rcfjp5kIY/6feDW/wG97ivrwJoEIt5xSE1TxhtorF0EhLt1ydQc4eTvPgGi8MbQP/HmcRGVjHSfw79VLfoXuVY/N9XHkUXCEw9GRCuH8AO8tW4pNeaakovQPsHZXsyQIDAQAB", "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
//        alipayRequest.setReturnUrl( "http://domain.com/CallBack/return_url.jsp" );
//        alipayRequest.setNotifyUrl( "http://domain.com/CallBack/notify_url.jsp" );
        //支付宝的回调地址,支付结果异步通知
        alipayRequest.setNotifyUrl( "http://e33676i991.qicp.vip/returlCallBack" ); //在公共参数中设置回跳和通知地址
        //alipayRequest.putOtherTextParam("app_auth_token", "201611BB8xxxxxxxxxxxxxxxxxxxedcecde6");//如果 ISV 代商家接入电脑网站支付能力，则需要传入 app_auth_token，使用第三方应用授权；自研开发模式请忽略
        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\"65654662132137875455112154642\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "    \"total_amount\":100000.00,"  +
                "    \"subject\":\"倚天剑\","  +
                "    \"body\":\"奥里给\","  +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","  +
                "    \"extend_params\":{"  +
                "    \"sys_service_provider_id\":\"2088511833207846\""  +
                "    }" +
                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        //return form;
        httpResponse.setContentType( "text/html;charset="  + "utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    @RequestMapping("/returlCallBack")
    public String returlCallBack(HttpServletRequest request , HttpResponse httpResp) throws AlipayApiException {
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhrm7VIVkEoAuS9U5QJgD3hD3oTYVpfNyWrJy5icqO0JsLmrmpuni6R0YXBZQGdAGYm1GMxzyAgTeMDEyrJGJUsGjiIAuY8Elv/nlqIdhzw27+OVSZWGUcWjXgFkg6ie7o87fwJG0roCkDRpR8+s5jYMDR54P1DPhHwjTGHviNSaGGJFNV9VKiB4//Mt5mSiD7HeiqT5CqVmhj6YtkZ+ydM0rcfjp5kIY/6feDW/wG97ivrwJoEIt5xSE1TxhtorF0EhLt1ydQc4eTvPgGi8MbQP/HmcRGVjHSfw79VLfoXuVY/N9XHkUXCEw9GRCuH8AO8tW4pNeaakovQPsHZXsyQIDAQAB/p/VwdGpb+bDSZU9pLEaSCzZTX6JqEeFo2fQav4mRVIY1FPgqOJ5Mn4AN/dB7j45Qy9wrIKh6+nP3dvDiN4wrHiobj4cl8Xb4vxbI3bvbj2SFYeL6u8iO49Hi4oXHvNaNzoKw8tl2hkI8N5sWU4LZAdT8odCSdpWwoMRvAapN+Doa4ceRgBmSc9D6l2qfz8Y0DIjd9wrs2fAc0XUUxb+JG1p5wGnzDagaNxFO8YkfeKlnaLtQ2ELQ2cy25db6sdNihIvXs6J3RzaU9kB4lHZwIDAQAB", "utf-8", "RSA2"); //调用SDK验证签名
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println(paramsMap);
          return "success";
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "fail";
        }
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
